package com.example.Pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.example.config.AlipayConfig;
import org.springframework.http.HttpRequest;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Alipay {
     //我是 你爸爸
    /*
    支付宝付款页面
     */
    public static String generatePCPAYHTML(String sn,Double total_Amount,String title,String info) throws UnsupportedEncodingException, AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = sn;
        //付款金额，必填
        String total_amount =total_Amount.toString();
        //订单名称，必填
        String subject = title;
        //商品描述，可空
        String body = info;
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no",sn);
        param.put("total_amount",total_Amount);
        param.put("subject",title);
        param.put("body",info);
        param.put("product_code","FAST_INSTANT_TRADE_PAY");
      alipayRequest.setBizContent(JSONObject.toJSONString(param));
//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//                + "\"total_amount\":\""+ total_amount +"\","
//                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求  将数据写入   网页中
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;

    }
    /*
    验证支付宝异步通知签名是不是合法
     */
    public static boolean isValidate(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println(signVerified);
        return signVerified;
    }
    /*
    查看订单详情
     */
    public static String viewDateil(String sn) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no",sn);
//
        //商户订单号，商户网站订单系统中唯一订单号
//        String out_trade_no = new String(request.getParameter("WIDTQout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        alipayRequest.setBizContent(JSONObject.toJSONString(param));

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
       return  result;
    }
    /*
    关闭订单
     */
    public static String closePay(String sn) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no",sn);
        //商户订单号，商户网站订单系统中唯一订单号
//        String out_trade_no = sn;


        alipayRequest.setBizContent(JSONObject.toJSONString(param));

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
         return result;
    }
    /*
    退款的接口
     */
    public static String refund(String sn,double refund_amount,String refund_info,String refundsn_sn) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no",sn);//商户订单号
        param.put("refund_reason",refund_info);//退款的原因
        param.put("out_request_no",refundsn_sn);//退款的编号

        param.put("refund_amount",String.valueOf(refund_amount));//退款的金额

        alipayRequest.setBizContent(JSONObject.toJSONString(param));

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }
}
